/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import entidade.persistencia.EntradaSaida;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.FolhaPagamento;
import entidade.persistencia.Manutencao;
import entidade.persistencia.Venda;
import java.util.List;
import entidade.persistencia.Compra;
import ws.converter.EntradaSaidaConverter;
import java.util.List;
/**
 *
 * @author victorinox
 */

public class EntradaSaidaResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of EntradaSaidaResource */
    public EntradaSaidaResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of EntradaSaida identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of EntradaSaidaConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public EntradaSaidaConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new EntradaSaidaConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of EntradaSaida identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an EntradaSaidaConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(EntradaSaidaConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of EntradaSaida identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of EntradaSaida identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of EntradaSaida
     */
    protected EntradaSaida getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (EntradaSaida) em.createQuery("SELECT e FROM EntradaSaida e where e.entradaSaidaId = :entradaSaidaId").setParameter("entradaSaidaId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected EntradaSaida updateEntity(EntradaSaida entity, EntradaSaida newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<Venda> vendaCollection = entity.getVendaCollection();
        List<Venda> vendaCollectionNew = newEntity.getVendaCollection();
        List<FolhaPagamento> folhaPagamentoCollection = entity.getFolhaPagamentoCollection();
        List<FolhaPagamento> folhaPagamentoCollectionNew = newEntity.getFolhaPagamentoCollection();
        List<Manutencao> manutencaoCollection = entity.getManutencaoCollection();
        List<Manutencao> manutencaoCollectionNew = newEntity.getManutencaoCollection();
        List<Compra> compraCollection = entity.getCompraCollection();
        List<Compra> compraCollectionNew = newEntity.getCompraCollection();
        entity = em.merge(newEntity);
        for (Venda value : vendaCollection) {
            if (!vendaCollectionNew.contains(value)) {
                value.getEntradaSaidaCollection().remove(entity);
            }
        }
        for (Venda value : vendaCollectionNew) {
            if (!vendaCollection.contains(value)) {
                value.getEntradaSaidaCollection().add(entity);
            }
        }
        for (FolhaPagamento value : folhaPagamentoCollection) {
            if (!folhaPagamentoCollectionNew.contains(value)) {
                value.getEntradaSaidaCollection().remove(entity);
            }
        }
        for (FolhaPagamento value : folhaPagamentoCollectionNew) {
            if (!folhaPagamentoCollection.contains(value)) {
                value.getEntradaSaidaCollection().add(entity);
            }
        }
        for (Manutencao value : manutencaoCollection) {
            if (!manutencaoCollectionNew.contains(value)) {
                value.getEntradaSaidaCollection().remove(entity);
            }
        }
        for (Manutencao value : manutencaoCollectionNew) {
            if (!manutencaoCollection.contains(value)) {
                value.getEntradaSaidaCollection().add(entity);
            }
        }
        for (Compra value : compraCollection) {
            if (!compraCollectionNew.contains(value)) {
                value.getEntradaSaidaCollection().remove(entity);
            }
        }
        for (Compra value : compraCollectionNew) {
            if (!compraCollection.contains(value)) {
                value.getEntradaSaidaCollection().add(entity);
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(EntradaSaida entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        for (Venda value : entity.getVendaCollection()) {
            value.getEntradaSaidaCollection().remove(entity);
        }
        for (FolhaPagamento value : entity.getFolhaPagamentoCollection()) {
            value.getEntradaSaidaCollection().remove(entity);
        }
        for (Manutencao value : entity.getManutencaoCollection()) {
            value.getEntradaSaidaCollection().remove(entity);
        }
        for (Compra value : entity.getCompraCollection()) {
            value.getEntradaSaidaCollection().remove(entity);
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of VendasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of VendasResource
     */
    @Path("vendaCollection/")
    public VendasResource getVendaCollectionResource() {
        VendaCollectionResourceSub resource = resourceContext.getResource(VendaCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of FolhaPagamentoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of FolhaPagamentoesResource
     */
    @Path("folhaPagamentoCollection/")
    public FolhaPagamentoesResource getFolhaPagamentoCollectionResource() {
        FolhaPagamentoCollectionResourceSub resource = resourceContext.getResource(FolhaPagamentoCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of ManutencaoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ManutencaoesResource
     */
    @Path("manutencaoCollection/")
    public ManutencaoesResource getManutencaoCollectionResource() {
        ManutencaoCollectionResourceSub resource = resourceContext.getResource(ManutencaoCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of ComprasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ComprasResource
     */
    @Path("compraCollection/")
    public ComprasResource getCompraCollectionResource() {
        CompraCollectionResourceSub resource = resourceContext.getResource(CompraCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class VendaCollectionResourceSub extends VendasResource {

        private EntradaSaida parent;

        public void setParent(EntradaSaida parent) {
            this.parent = parent;
        }

        @Override
        protected List<Venda> getEntities(int start, int max, String query) {
            List<Venda> result = new java.util.ArrayList<Venda>();
            int index = 0;
            for (Venda e : parent.getVendaCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class FolhaPagamentoCollectionResourceSub extends FolhaPagamentoesResource {

        private EntradaSaida parent;

        public void setParent(EntradaSaida parent) {
            this.parent = parent;
        }

        @Override
        protected List<FolhaPagamento> getEntities(int start, int max, String query) {
            List<FolhaPagamento> result = new java.util.ArrayList<FolhaPagamento>();
            int index = 0;
            for (FolhaPagamento e : parent.getFolhaPagamentoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class ManutencaoCollectionResourceSub extends ManutencaoesResource {

        private EntradaSaida parent;

        public void setParent(EntradaSaida parent) {
            this.parent = parent;
        }

        @Override
        protected List<Manutencao> getEntities(int start, int max, String query) {
            List<Manutencao> result = new java.util.ArrayList<Manutencao>();
            int index = 0;
            for (Manutencao e : parent.getManutencaoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class CompraCollectionResourceSub extends ComprasResource {

        private EntradaSaida parent;

        public void setParent(EntradaSaida parent) {
            this.parent = parent;
        }

        @Override
        protected List<Compra> getEntities(int start, int max, String query) {
            List<Compra> result = new java.util.ArrayList<Compra>();
            int index = 0;
            for (Compra e : parent.getCompraCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
